<template>
  <div id="score-view-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="header">
      <el-form-item label="班级名">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名"
          clearable
        />
      </el-form-item>
      <el-form-item label="学号">
        <el-input
          v-model="queryParams.studentAccount"
          placeholder="请输入学号"
          clearable
        />
      </el-form-item>
      <el-form-item label="课程名">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名"
          clearable
        />
      </el-form-item>
      <el-form-item label="学期">
        <el-select
          v-model="queryParams.semesterId"
          placeholder="请选择学期"
          @change="handleSemesterChange"
          clearable
        >
          <el-option
            v-for="semester in semesterList"
            :key="semester.id"
            :label="semester.year + '学年第' + semester.term + '学期'"
            :value="semester.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有效">
        <el-select
          v-model="queryParams.isValid"
          placeholder="请选择状态"
          @change="handleIsValidChange"
          clearable
        >
          <el-option :value="1" label="有效" />
          <el-option :value="0" label="无效" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getScoreList">查询</el-button>
        <el-button type="warning" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="el-icon-download" @click="batchExport"
          >批量导出成绩</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 成绩列表 -->
    <div class="content">
      <el-table :data="tableData" border size="small" style="width: 100%">
        <el-table-column prop="className" label="班级" align="center" />
        <el-table-column prop="studentAccount" label="学号" align="center" />
        <el-table-column prop="studentName" label="姓名" align="center" />
        <el-table-column prop="courseName" label="课程" align="center" />
        <el-table-column prop="teacherName" label="授课教师" align="center" />
        <el-table-column prop="score" label="成绩" align="center">
          <template slot-scope="scope">
            <template
              v-if="scope.row.score !== null && scope.row.score !== undefined"
            >
              <span :class="getScoreClass(scope.row.score)">
                {{ scope.row.score }}
                <el-tag
                  size="mini"
                  :type="getScoreTagType(scope.row.score)"
                  style="margin-left: 5px"
                >
                  {{ getScoreLevel(scope.row.score) }}
                </el-tag>
              </span>
            </template>
            <template v-else>
              <el-tag size="mini" type="info"> 未录入 </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="semester" label="学期" align="center" />
        <el-table-column prop="examTime" label="考试日期" align="center" />
        <el-table-column prop="isValid" label="状态" align="center">
          <template slot-scope="scope">
            <template
              v-if="scope.row.score !== null && scope.row.score !== undefined"
            >
              <el-tag
                :type="Number(scope.row.isValid) === 1 ? 'success' : 'danger'"
              >
                {{ Number(scope.row.isValid) === 1 ? "有效" : "无效" }}
              </el-tag>
            </template>
            <template v-else>
              <span></span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" align="center" />
      </el-table>
      <el-pagination
        class="table-pagination"
        background
        layout="total, prev, pager, next, jumper, sizes"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import { queryScores, exportScores } from "@/api/score";
import { getAllSemester } from "@/api/semester";
import { mapState } from "vuex";

export default {
  computed: {
    ...mapState("user", ["userInfo"]),
    // isStudent() {
    //   return this.userInfo.roleId === 3; // 假设roleId 3表示学生角色
    // },
  },
  data() {
    return {
      queryParams: {
        className: "",
        studentAccount: "",
        courseName: "",
        semesterId: null,
        isValid: null,
        pageNo: 1,
        pageSize: 10,
      },
      tableData: [],
      total: 0,
      semesterList: [],

      distributionOptions: {},
      averageOptions: {},
      statusOptions: {},

      fullscreenLoading: false, // 导出数据时的遮罩层
    };
  },
  methods: {
    async batchExport() {
      try {
        this.fullscreenLoading = true;
        this.$message.info("正在导出成绩数据，请稍候...");
        const response = await exportScores(this.queryParams);

        // 创建Blob对象
        const blob = new Blob([response], { type: "application/vnd.ms-excel" });

        // 创建下载链接
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);

        // 设置文件名
        const now = new Date();
        const fileName = `成绩数据_${now.getFullYear()}${(now.getMonth() + 1)
          .toString()
          .padStart(2, "0")}${now.getDate().toString().padStart(2, "0")}.xlsx`;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success("成绩数据导出成功");
      } catch (error) {
        console.error("导出失败:", error);
        this.$message.error("成绩数据导出失败，请稍后重试");
      } finally {
        this.fullscreenLoading = false;
      }
    },

    resetQuery() {
      this.queryParams = {
        className: "",
        studentAccount: this.isStudent ? this.userInfo.account : "",
        courseName: "",
        semesterId: null,
        isValid: null,
        pageNo: 1,
        pageSize: 10,
      };
      // 重置后立即查询所有成绩
      this.getScoreList();
    },

    // 学期选择改变时的处理函数
    handleSemesterChange() {
      // 当学期改变时立即查询
      this.getScoreList();
    },

    async getScoreList() {
      // 如果是学生角色，自动填充学号
      if (this.isStudent) {
        this.queryParams.studentAccount = this.userInfo.account;
      }

      const res = await queryScores(this.queryParams);
      if (res.code === 200) {
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },
    async getSemesterList() {
      const res = await getAllSemester();
      if (res.code === 200) {
        this.semesterList = res.data;
      }
    },
    handleCurrentChange(page) {
      this.queryParams.pageNo = page;
      this.getScoreList();
    },
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.queryParams.pageNo = 1;
      this.getScoreList();
    },
    isAbnormalScore(row) {
      // 这里可以定义异常成绩的判断逻辑，比如成绩超过某个范围
      return row.score < 0 || row.score > 100; // 示例
    },

    // 获取成绩对应的CSS类
    getScoreClass(score) {
      if (score < 60) return "score-fail";
      if (score >= 90) return "score-excellent";
      return "score-pass";
    },

    // 获取成绩等级标签文本
    getScoreLevel(score) {
      if (score < 60) return "不及格";
      if (score >= 90) return "优秀";
      return "及格";
    },

    // 获取成绩等级标签类型
    getScoreTagType(score) {
      if (score < 60) return "danger";
      if (score >= 90) return "success";
      return "primary";
    },

    // 是否有效选择改变时的处理函数
    handleIsValidChange() {
      this.getScoreList();
    },
  },
  mounted() {
    this.getSemesterList();

    // 如果是学生角色，自动填充学号
    /*   if (this.isStudent) {
      this.queryParams.studentAccount = this.userInfo.account;
    } */

    this.getScoreList();
  },
};
</script>

<style lang="scss" scoped>
#score-view-container {
  margin: 20px;

  .score-fail {
    color: #f56c6c; /* 红色 */
    font-weight: bold;
  }

  .score-pass {
    color: #409eff; /* 蓝色 */
  }

  .score-excellent {
    color: #67c23a; /* 绿色 */
    font-weight: bold;
  }

  .header {
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
  }

  .content {
    margin-top: 20px;

    .table-pagination {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }

    .abnormal-score {
      color: red;
      font-weight: bold;
    }
  }
}
</style>